package com.bw.test_bluetooth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresPermission
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.UUID

/**
 * 蓝牙：
 * 1.打开蓝牙、关闭蓝牙
 * 2.扫描附近蓝牙设备
 * 3.配对
 * 4.传输数据：输入输出流实现发送数据和接受数据
 *  A链接B
 *  A客户端：BlueToothSocket
 *  B服务端：BlueToothServerSocket
 *  A发送数据给B：A输出流写入数据 B输入流读取数据
 *  B发送数据给A：B输出流写入数据 A输入流读取数据
 *
 *
 */
class MainActivity : AppCompatActivity() {
    companion object{
        const val TAG = "MainActivity"
    }
    private lateinit var bluetoothAdapter: BluetoothAdapter //本机蓝牙适配器
    private lateinit var myReceiver: MyReceiver
    private lateinit var mDiscoverRV: RecyclerView
    private lateinit var mBondedRV: RecyclerView
    private lateinit var mDiscoverAdapter: BlueToothDeviceAdapter
    private lateinit var mBondedAdapter: BlueToothDeviceAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //1：动态权限
        requestPermissions()
        //2:获得本机蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null){
            Toast.makeText(this,"本机没有蓝牙设备",Toast.LENGTH_SHORT).show()
        }
        //2.启动服务端能够接受别人链接
        val serverThread = ServerThread(bluetoothAdapter)
        serverThread.start()
        //3：注册广播
        myReceiver = MyReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
        registerReceiver(myReceiver,intentFilter)
        //列表
        mDiscoverRV = findViewById(R.id.rv_discovery)
        mBondedRV = findViewById(R.id.rv_bonded)
        mDiscoverAdapter = BlueToothDeviceAdapter{device->
            Toast.makeText(this,"去配对: ${device.name} ${device.address}",Toast.LENGTH_SHORT).show()
            //配对
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return@BlueToothDeviceAdapter
            }
            device.createBond()
        }
        mBondedAdapter = BlueToothDeviceAdapter{device->
            //传输数据
            sendFile(device)
        }
        mDiscoverRV.adapter = mDiscoverAdapter
        mBondedRV.adapter = mBondedAdapter
        mDiscoverRV.layoutManager = LinearLayoutManager(this)
        mBondedRV.layoutManager = LinearLayoutManager(this)


    }

    /**
     * 发送数据
     */
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    private fun sendFile(device: BluetoothDevice) {
        //客户端
        val bluetoothSocket =
            device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
        bluetoothSocket.connect()
        //输出流发送数据
        Thread{
            bluetoothSocket.outputStream.write("HELLO".toByteArray())
//            bluetoothSocket.outputStream.flush()
//            bluetoothSocket.outputStream.close()
//            bluetoothSocket.close()
        }.start()

    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(myReceiver) //解除注册：防止内存泄露
    }
    private fun requestPermissions() {
        val permissions = arrayOf(
            Manifest.permission.BLUETOOTH_SCAN,
            android.Manifest.permission.BLUETOOTH,
            android.Manifest.permission.BLUETOOTH_ADMIN,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.BLUETOOTH_CONNECT,
        )
        permissions.forEach {
            if (checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, 1)
            }
        }
    }

    /**
     * 打开蓝牙
     */
    fun open(view: View) {
        if (bluetoothAdapter.isEnabled){
            Toast.makeText(this,"蓝牙已打开",Toast.LENGTH_SHORT).show()
            return
        }
        val intent = Intent()
        intent.action = BluetoothAdapter.ACTION_REQUEST_ENABLE // 打开蓝牙
        intent.action = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE //被扫描
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200) //200S
        startActivity(intent)
    }

    /**
     * 关闭蓝牙
     */
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun close(view: View) {
        if (!bluetoothAdapter.isEnabled){
            Toast.makeText(this,"蓝牙已关闭",Toast.LENGTH_SHORT).show()
            return
        }
        bluetoothAdapter.disable()
    }

    /**
     * 扫描附近蓝牙设备-->发送系统广播---》广播接收器
     */
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun scan(view: View) {
        bluetoothAdapter.startDiscovery()
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun getBonded(view:View){
        val devices = bluetoothAdapter.bondedDevices
//        for (device in devices){
//            Log.d(TAG, "已配对设备: ${device.name} ${device.address}")
//        }
        mBondedAdapter.setData(devices.toList())

    }
    /**
     * 广播接收器
     */

    inner class MyReceiver: BroadcastReceiver(){
        @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == BluetoothDevice.ACTION_FOUND){ //扫描到一个新设备
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) //获得扫描到远程设备
                //TODO 获取设备名称和地址
                Log.d(TAG, "扫描到设备: ${device?.name} ${device?.address}")
                device?.let {
                    mDiscoverAdapter.addData(it)
                }

            }
        }
    }




}